//
//  LiuEmoticonCollectionView.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/4/6.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit





class LiuEmoticonFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        itemSize = CGSize(width: (collectionView?.width)!, height: (collectionView?.height)!)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
    }
}

class LiuEmoticonCollectionView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate {
    
    //滚动视图回调,改变pagecontrol
    var scrollPageClosure: ((IndexPath)->())?
    
    
    //滚动视图的时候回调
    var scrollClosure: ((Int)->())?
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = LiuEmoticonFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI() {
        
        //设置背景
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        //滚动条,弹簧效果,分页效果
        showsVerticalScrollIndicator = false
        showsHorizontalScrollIndicator = false
        isPagingEnabled = true
        bounces = false
        
        //数据源,代理
        delegate = self
        dataSource = self
        
        register(LiuEmoticonViewCell.self, forCellWithReuseIdentifier: emoticonCellId)
        
        //默认状态下滚动到第二组"默认图片",需要主线程异步执行
        DispatchQueue.main.async { 
            let indexpath = IndexPath(item: 0, section: 1)
            self.scrollToItem(at: indexpath, at: [], animated: false)
        }
        
        
        
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return LiuEmoticonTool.sharedEmoticonManager.emoticonArray.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LiuEmoticonTool.sharedEmoticonManager.emoticonArray[section].count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:LiuEmoticonViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: emoticonCellId, for: indexPath) as! LiuEmoticonViewCell
        
        cell.emojiImage = LiuEmoticonTool.sharedEmoticonManager.emoticonArray[indexPath.section][indexPath.item]
        
        return cell
        
    }
    
    //给外界一个借口,调整offset
    func changeOffset(type:LiuEmoticonType) {
        
        let indexPath:IndexPath
        switch type {
        case .recent:
            indexPath = IndexPath(item: 0, section: 0)
        case .normal:
            indexPath = IndexPath(item: 0, section: 1)
        case .emoji:
            indexPath = IndexPath(item: 0, section: 2)
        case .lxh:
            indexPath = IndexPath(item: 0, section: 3)
        }
        
        //滚动
        scrollToItem(at: indexPath, at: [], animated: false)
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //判断是否需要刷新数据
        if scrollView.contentOffset.x <= 0 {
            reloadData()
        }
 
        //代码执行到此,说明是手动拖拽滚动的
        //在屏幕中间显示的点
        let pointX = scrollView.contentOffset.x + width/2
        
        //判断这个点是否在cell上,如果在回调组数
        if let indexPath = indexPathForItem(at: CGPoint(x: pointX, y: 0)) {
            let section = indexPath.section
            
            scrollPageClosure?(indexPath)
            
            //判断是手动滚动还是由于点击toolbar按钮滚动(自动滚动)
            if !scrollView.isDragging && !scrollView.isTracking && !scrollView.isDecelerating {
                //是自动
                return
            }
            scrollClosure?(section)
        }
        
    }
    
    
    
    

}

class LiuEmoticonViewCell: UICollectionViewCell {
    
    //懒加载删除按钮
    fileprivate lazy var deleteButton:UIButton  = {
        let button = UIButton()
        button.setImage(UIImage(named:"compose_emotion_delete"), for: .normal)
        button.setImage(UIImage(named:"compose_emotion_delete_highlighted"), for: .highlighted)
        
        //添加点击事件
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        return button
    }()
    
    //懒加载控件
    fileprivate lazy var buttonArray:[UIButton] = [UIButton]()
    
    var emojiImage:[LiuEmoticonModel]? {
        didSet {
            
            //隐藏所有按钮
            for button in buttonArray {
                button.isHidden = true
            }
            
            //遍历收到的数组,给自身按钮赋值图片
            guard let array = emojiImage else {
                return
            }
            for (i,model) in array.enumerated() {
                
                //显示对应的按钮
                buttonArray[i].isHidden = false
                
                //判断是否是图片表情
                if model.type == "0" {
                    
                    //文字nil
                    buttonArray[i].setTitle(nil, for: .normal)
                    //图片表情
                    buttonArray[i].setImage(UIImage(named:MainbundlePath! + model.partPath!), for: .normal)
                    
                } else {
                    
                    //图片nil
                    buttonArray[i].setImage(nil, for: .normal)
                    //emoji表情
                    buttonArray[i].setTitle((model.code! as NSString).emoji(), for: .normal)
                }
            }
        }
    }
    
    
    //
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI() {
        addChildButton()
        contentView.addSubview(deleteButton)
    }
    
    //添加20个button
    fileprivate func addChildButton() {
        
        for i in 0..<20 {
            let button = UIButton()
            button.tag = 10 + i
            button.titleLabel?.font = UIFont.systemFont(ofSize: 33)
            buttonArray.append(button)
            contentView.addSubview(button)
            
            //添加点击事件
            button.addTarget(self, action: #selector(buttonAction(btn:)), for: .touchUpInside)
            
        }
    }
    
    override func layoutSubviews() {
        
        let itemWidth = width/7
        let itemHeight = height/3
        
        for (i,button) in buttonArray.enumerated() {
            
            let itemX = CGFloat(i%7) * itemWidth
            let itemY = CGFloat(i/7) * itemHeight
            
            button.frame = CGRect(x: itemX, y: itemY, width: itemWidth, height: itemHeight)
        }
        
        //设置删除按钮的大小和位置
        deleteButton.size = CGSize(width: itemWidth, height: itemHeight)
        deleteButton.x = width - itemWidth
        deleteButton.y = height - itemHeight
        
    }
    
    //点击事件
    @objc fileprivate func buttonAction(btn:UIButton) {
        
        let emoticon = emojiImage![btn.tag - 10]
        
        //点击按钮,在textView上显示,发送通知
        NotificationCenter.default.post(name: NSNotification.Name(emoticonButtonNotification), object: emoticon)
        
        //将按钮对应的model添加到"最近"中 
        LiuEmoticonTool.sharedEmoticonManager.saveRecentEmoticon(emoticon: emoticon)
        
        
    }
    
    //删除按钮点击事件
    @objc fileprivate func deleteButtonAction() {
        
        //发送通知,告诉textView删除
        NotificationCenter.default.post(name: NSNotification.Name(emoticonDeleteButtonNotification), object: nil)
    }
    
    
    
}









